package www.reagnetbox.com.util;

import android.content.Context;
import android.os.Environment;

import com.blankj.utilcode.util.SPUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.FileCallBack;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.File;
import java.util.Map;

import okhttp3.Call;

public class NetUtil {

    public static void post(Context context, String api, Map<String, String> params, www.reagnetbox.com.callback.StringCallback callback) {
        String base = SPUtils.getInstance().getString("base");
        if (base.equals("")){
            XPopupUtil.showKnowPopup(context,"请先设置Lims接口地址");
            return;
        }


        XPopupUtil.startLoading(context, null);
        OkHttpUtils
                .post()
                .url(base + api)
//                .headers(headers)
                .params(params)
                .build()
                .execute(new StringCallback() {

                    @Override
                    public void onError(Call call, Exception e, int id) {
                        XPopupUtil.stopLoading();
                        XPopupUtil.showKnowPopup(context, "网络请求失败：" + e.getMessage() );
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        XPopupUtil.stopLoading();
                        callback.fun(response);
                    }
                });
    }

    public static void download(Context context, String fileName, String url) {
        XPopupUtil.startLoading(context, "下载中...");
        OkHttpUtils//
                .get()//
                .url(url)//
                .build()//
                .execute(new FileCallBack(Environment.getExternalStorageDirectory().getAbsolutePath(), fileName) {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        XPopupUtil.stopLoading();
                        XPopupUtil.showKnowPopup(context, "下载失败：" + e.getMessage() );
                    }

                    @Override
                    public void onResponse(File file, int id) {
                        XPopupUtil.stopLoading();
                        if (file != null) {
                            XPopupUtil.showKnowPopup(context, "下载成功" );
                        }
                    }
                });
    }
}
